import React, {useState, useEffect} from 'react';
import {
    NavBar,
    Modal,
    List,
    InputItem,
    Picker,
    Icon,
    Button,
    Checkbox,
    WhiteSpace,
    Toast,
    TextareaItem
} from 'antd-mobile';

import {sexList, regionList, R, VOID} from '../../../assets/js/dict'; // 公用字典
import {
    PostSignIn,
    GetCheckCode,
    GetCheckPhoneForParentSignIn,
    GetPhoneCodeForSignIn,
    parentProtocolHtml,
    PostParentLogin
} from "@/api/login.js"; // login api

import {createForm} from 'rc-form';

import _ from "lodash"

import './signUp.scss';

const Item = List.Item;
const Brief = Item.Brief;
const AgreeItem = Checkbox.AgreeItem;

const dict = {
    name: "姓名",
    gender: "性别",
    code: "图形验证码",
    phone: "手机",
    verifyCode: "短信验证码",
    area: "居住区域",
    site: "地址",
    password: "密码",
    repassword: "确认密码"
};

function SignUp(props) {
    const [SignUpFormRule, SetSignUpFormRule] = useState({});
    const [imgObject, SetImgObject] = useState({})
    const [isCheckout, SetIsCheckout] = useState(false)
    let [couldSend, updateSend] = useState(true);
    let [btn, setBtn] = useState("发送");

    //控制用户须知的显隐
    let [showVisi, setShowVisi] = useState(false);

    let [closeBtn, setCloseBtn] = useState(false);

    let [knowHtml, setKnowHtml] = useState("");

    function showNotice() {
        setShowVisi(true);
    }

    function hideNotice() {
        let target = handle['notice'];
        let scrollTop = target.scrollTop;
        target.scrollTo(0, -scrollTop);
        setShowVisi(false);
    }

    function agreeNotice() {
        hideNotice();
        SetIsCheckout(true);
    }


    // 获取注册用的图形验证码
    function axiosGetCheckCode() {
        GetCheckCode({}, (res) => {
            if (R.isSuccess(res)) {
                SetImgObject(res.responseData)

                // 设置验证码过期刷新
                let timeout = res.responseData.timeout;
                if (timeout > 10) {
                    setTimeout(() => axiosGetCheckCode(), (timeout - 10) * 1000);
                }
            }
        });
    }


    // 注册
    function handleLogin() {
        let postData = props.form.getFieldsValue().SignUpForm;
        if (postData.repassword !== postData.password) {
            Toast.fail("两次输入的密码不一致");
            return;
        }
        let words = [], seq = 1, item;
        for (let key in dict) {
            item = postData[key];
            if (null === item || undefined === item || /^\s*$/.test(item)) {
                words.push(<span key={key} style={{marginLeft: '0.7rem'}}><strong
                    key={key + 's'}
                >({seq++}){" " + dict[key]}</strong><br/></span>);
            }
        }
        if (words.length > 0) {
            Modal.alert('检测到有未完成的项', <p style={{textAlign: 'left'}}>{words}</p>,
                [{
                    text: '关闭', onPress: () => {
                    }
                }, {
                    text: '忽略警告', onPress: () => {
                        doSign(postData);
                    }
                }]);
        } else {
            doSign(postData);
        }

    };

    function doSign(postData) {
        try {
            if (postData.area) {
                postData.region = postData.area[0];
            }
            postData.role = props.match.params.role;
            if (postData.gender) {
                postData.gender = String(postData.gender);
            }
            if (postData.phone) {
                postData.phone = postData.phone.replace(/\s+/g, "");
            }
            postData.wx_open_id = localStorage.getItem("openid");
        } catch (e) {
            console.error(e)
        }
        PostSignIn(postData, (res) => {
            if (res.code === "888168" && res.responseData) {
                let info = res.responseData, words = [], seq = 1;
                for (let i in info) {
                    words.push(<span key={i} style={{marginLeft: '0.7rem'}}><strong
                        key={i + 's'}
                    >({seq++}){" " + info[i]}</strong><br/></span>);
                }
                Modal.alert('注册失败', <p style={{textAlign: 'left'}}>{words}</p>);
                SetSignUpFormRule(info);
            } else if (R.isSuccess(res)) {
                let user = R.getData(res);
                sessionStorage.setItem('userInfo', JSON.stringify({
                    id: user.id,
                    isPass: false,
                    isVip: user.is_vip,
                    vip_limit: user.vip_limit,
                    openid: user.wx_open_id,
                    username: user.name,
                    type: user.role,
                }));

                //执行登录
                Toast.success("注册成功", 2, () => {
                    PostParentLogin({username: user.name, password: postData.password}).then(res => {
                        if (res.code === "000000") {
                            props.history.push("/main");
                        }
                    })
                });

            }
        })
    }


    //发送短信验证码
    function handleGetPhoneCodeForSignIn() {
        let postData = {};
        let phone = props.form.getFieldsValue().SignUpForm.phone;
        if (phone) {
            postData.phone = phone.replace(/\s+/g, "");
        } else {
            Toast.fail("请填写手机号码", 1);
            return;
        }
        let code = props.form.getFieldsValue().SignUpForm.code;
        postData.flag = imgObject.key;
        if (!!code) {
            postData.code = code;
        } else {
            Toast.fail("请填写图形验证码", 1);
            return;
        }
        GetCheckPhoneForParentSignIn(postData, (res) => {
            if (R.isSuccess(res)) {
                let re = R.getData(res);
                if (re > 0) {
                    Toast.fail("手机号已经被使用，请使用其它号码", 3, VOID, false);
                } else {
                    GetPhoneCodeForSignIn(postData, (res) => {
                        if (R.isSuccess(res)) {
                            Toast.success("验证码已发送，请您注意查收短信", 2, VOID, false);
                            let count = 60;
                            setBtn(`发送(${count})`);

                            //设置短信发送按键为不可以点击
                            updateSend(false);
                            let c = setInterval(() => {
                                count--;
                                if (count === 0) {
                                    clearInterval(c);
                                    setBtn("发送");

                                    //设置短信发送按键为可以点击
                                    updateSend(true);

                                } else {
                                    setBtn(`发送(${count})`);

                                    //设置短信发送按键为不可以点击
                                    updateSend(false);
                                }
                            }, 1000);

                            //刷新图形验证码
                            axiosGetCheckCode();
                        }
                    })
                }
            }
        })
    }

    /**
     * 获取用户须知
     */
    function getNotice() {
        parentProtocolHtml({}, (res) => {
            if (R.isSuccess(res)) {
                setKnowHtml(R.getData(res));
            }
        });
    }

    // 把 useEffect Hook 看做 componentDidMount，componentDidUpdate 和 componentWillUnmount 这三个函数的组合
    useEffect(() => {
        axiosGetCheckCode();
        getNotice();
    }, []);

    const {getFieldProps} = props.form;

    //缓存组件的ref
    let handle = {};


    /**
     * 同意协议
     * @param e
     */
    function agree(e) {
        if (e.target.checked) {
            SetIsCheckout(true);
        } else {
            SetIsCheckout(false);
        }
    }

    function back() {
        props.history.goBack()
    }


    function checkPwd(pwd) {
        console.log("checkPwd--->", pwd);
        if (!!pwd) {
            if (!/^(?![A-Za-z]+$)(?![\d]+$)(?![\d\W]+$)[a-zA-Z0-9\W]{6,}$/.test(pwd)) {
                SignUpFormRule.password = "密码安全性不足，密码长度至少6位，且必须由字母和数字构成";
                SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
            } else {
                SignUpFormRule.password = "";
                let obj = props.form.getFieldsValue().SignUpForm;
                if (pwd === obj.repassword) {
                    SignUpFormRule.repassword = "";
                }
                SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
            }
        }
    }

    function checkRePwd(pwd) {
        console.log("checkRePwd--->", pwd);
        if (!!pwd) {
            if (!/^(?![A-Za-z]+$)(?![\d]+$)(?![\d\W]+$)[a-zA-Z0-9\W]{6,}$/.test(pwd)) {
                SignUpFormRule.repassword = "密码安全性不足，密码长度至少6位，且必须由字母和数字构成";
                SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
            } else {
                let obj = props.form.getFieldsValue().SignUpForm;
                if (pwd !== obj.password) {
                    SignUpFormRule.repassword = "两次输入的密码不一致";
                    SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
                } else {
                    SignUpFormRule.repassword = "";
                    SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
                }
            }
        }
    }

    function onScroll(event) {
        let target = event.target;
        let scrollTop, maxScroll;
        scrollTop = target.scrollTop;
        maxScroll = target.scrollHeight - target.offsetHeight;
        if (scrollTop >= maxScroll) {
            setCloseBtn(true);
        }
    }

    function onBlur(value, field) {
        console.log("onBlur--->", value, field);
        if (!!value) {
            SignUpFormRule[field] = false;
            SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
        } else {
            SignUpFormRule[field] = dict[field] + "不能为空";
            SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
        }
    }

    function nameBlur(v) {
        onBlur(v, 'name');
    }

    function phoneBlur(value) {
        if (!!value) {
            let phone= value.replace(/\s+/g, '');
            if(/^1\d{10}$/.test(phone)){
                SignUpFormRule['phone'] = false;
                SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
            }else {
                SignUpFormRule['phone'] = '手机号码格式不正确';
                SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
            }
        } else {
            SignUpFormRule['phone'] = "手机号码不能为空";
            SetSignUpFormRule(_.cloneDeep(SignUpFormRule));
        }
    }

    function siteBlur(v) {
        onBlur(v, 'site');
    }

    function areaBlur(v) {
        onBlur(v, 'area');
    }

    function codeBlur(v) {
        onBlur(v, 'code');
    }

    function verifyCodeBlur(v) {
        onBlur(v, 'verifyCode');
    }

    return (
        <div>
            <div
                ref={(el) => {
                    handle['notice'] = el;
                }}
                className="helpDetails"
                style={{overflow: 'auto', height: 'calc(100vh - 42px)', display: showVisi ? 'block' : 'none'}}
                onScroll={onScroll}
            >
                <div className="page-title helpDetails-tit">
                    <NavBar
                        mode="light"
                        rightContent={
                            <span key="close"
                                  onClick={hideNotice}
                            >关闭</span>
                        }
                    >
                        注册须知
                    </NavBar>
                </div>
                <div className="page-content helpDetails-con" dangerouslySetInnerHTML={{__html: knowHtml}}/>
                <WhiteSpace size="xl"/>
                <WhiteSpace size="xl"/>
                <div className="form-footer">
                    <AgreeItem data-seed="logId" value={!!isCheckout} onChange={agree} checked={!!isCheckout}>
                        &nbsp;
                        <span>同意以上协议</span>
                    </AgreeItem>
                    <Button type="primary" onClick={agreeNotice}>{isCheckout ? '确定' : '同意并继续'}</Button>
                </div>
            </div>

            <div className="SignUp" style={{display: showVisi ? 'none' : 'block'}}>

                <div className="page-title">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left"/>}
                        onLeftClick={back}
                    >
                        注册
                    </NavBar>
                </div>
                <div className="page-content">
                    <div className="form-box">
                        <div className="form-con">
                            <List>
                                <InputItem
                                    {...getFieldProps('SignUpForm.name')}
                                    clear
                                    ref={el => {
                                        handle["name"] = el;
                                    }}
                                    placeholder="请输入姓名"
                                    onBlur={nameBlur}
                                    error={SignUpFormRule.name}
                                    onErrorClick={() => {
                                        Toast.info(SignUpFormRule.name);
                                    }}
                                >
                                    姓名
                                </InputItem>
                                <WhiteSpace size="md"/>
                                <Picker
                                    data={sexList}
                                    cols={1}
                                    {...getFieldProps('SignUpForm.gender', {initialValue: [sexList[0].value]})}
                                >
                                    <List.Item arrow="horizontal">性別</List.Item>
                                </Picker>
                                <WhiteSpace size="md"/>
                                <InputItem
                                    labelNumber={6}
                                    error={SignUpFormRule.code}
                                    onErrorClick={() => Toast.info(SignUpFormRule.code)}
                                    extra={<img style={{
                                        width: '90px',
                                        height: 'auto',
                                        float: 'right',
                                        marginLeft: '10px'
                                    }} src={'data:image/png;base64,' + imgObject.img}
                                                onClick={axiosGetCheckCode}
                                    />}
                                    {...getFieldProps('SignUpForm.code', {initialValue: ''})}
                                    placeholder="请输入图形验证码"
                                >
                                    图形码
                                </InputItem>
                                <WhiteSpace size="md"/>
                                <InputItem
                                    type="phone"
                                    {...getFieldProps('SignUpForm.phone')}
                                    placeholder="请输入手机号码"
                                    clear
                                    ref={el => {
                                        handle["phone"] = el;
                                    }}
                                    onBlur={phoneBlur}
                                    error={SignUpFormRule.phone}
                                    onErrorClick={() => {
                                        Toast.info(SignUpFormRule.phone);
                                    }}
                                >
                                    手机
                                </InputItem>
                                <WhiteSpace size="md"/>
                                <InputItem
                                    type="digit"
                                    placeholder="请输入短信验证码"
                                    labelNumber={6}
                                    onBlur={verifyCodeBlur}
                                    error={SignUpFormRule.verifyCode}
                                    onErrorClick={() => {
                                        Toast.info(SignUpFormRule.verifyCode);
                                    }}
                                    extra={<Button type="primary" activeStyle={couldSend} disabled={!couldSend}
                                                   loading={!couldSend} size="small" inline
                                                   onClick={handleGetPhoneCodeForSignIn}
                                                   style={{
                                                       textAlign: 'center',
                                                       top: '0',
                                                       bottom: '0',
                                                       marginLeft: '0.3rem'
                                                   }}
                                    >
                                        {btn}
                                    </Button>}
                                    {...getFieldProps('SignUpForm.verifyCode', {initialValue: ''})}
                                >
                                    短信验证码
                                </InputItem>
                                <WhiteSpace size="md"/>
                                <Picker
                                    data={regionList}
                                    title="居住区域"
                                    cols={1}
                                    {...getFieldProps('SignUpForm.area', {initialValue: [regionList[0].value]})}

                                >
                                    <List.Item arrow="horizontal">居住区域</List.Item>
                                </Picker>
                                <WhiteSpace size="md"/>
                                <TextareaItem
                                    {...getFieldProps('SignUpForm.site')}
                                    title="地址"
                                    placeholder="请输入详细地址(需要具体到小区名)"
                                    clear
                                    ref={el => {
                                        handle["site"] = el;
                                    }}
                                    onBlur={siteBlur}
                                    error={SignUpFormRule.site}
                                    onErrorClick={() => Toast.info(SignUpFormRule.site)}
                                    autoHeight
                                />
                                <WhiteSpace size="md"/>
                                <Item multipleLine>
                                    设置密码
                                    <Brief>
                                        <InputItem
                                            {...getFieldProps('SignUpForm.password')}
                                            clear
                                            ref={el => {
                                                handle["password"] = el;
                                            }}
                                            placeholder="密码长度至少6位，且必须由字母和数字构成"
                                            error={SignUpFormRule.password}
                                            onBlur={checkPwd}
                                            type="password"
                                            onErrorClick={() => {
                                                Toast.info(SignUpFormRule.password);
                                            }}
                                        />
                                    </Brief>
                                </Item>
                                <WhiteSpace size="md"/>
                                <Item multipleLine>
                                    确认密码
                                    <Brief>
                                        <InputItem
                                            {...getFieldProps('SignUpForm.repassword')}
                                            clear
                                            ref={el => {
                                                handle["repassword"] = el;
                                            }}
                                            placeholder="请再次输入密码"
                                            type="password"
                                            onBlur={checkRePwd}
                                            error={SignUpFormRule.repassword}
                                            onErrorClick={() => {
                                                Toast.info(SignUpFormRule.repassword);
                                            }}
                                        />
                                    </Brief>
                                </Item>
                            </List>
                        </div>
                        <WhiteSpace size="xl"/>
                        <div className="form-footer">
                            <AgreeItem data-seed="logId" value={!!isCheckout} checked={!!isCheckout} disabled>
                                &nbsp;
                                <a onClick={showNotice}>
                                    用户协议
                                </a>
                                <p style={{margin: 0}}>请进入详情页阅读后进行勾选</p>
                            </AgreeItem>
                            <Button type="primary" onClick={handleLogin} disabled={!isCheckout}>注册</Button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

SignUp = createForm()(SignUp);

export default SignUp;